<?php

function print_error( $msg )
	{
		print <<<END
		<tr>
			<td colspan=5><font color=red><b>Error: </b></font>$msg</td>
			<td><font color=red><b>Rejected</b></font></td>
		</tr>

END;
	}

function getHeader( $exc, $data )
{
		// string
	
		$ind = $data['data'];
		if( $exc->sst[unicode][$ind] )
			return convertUnicodeString ($exc->sst['data'][$ind]);
		else
			return $exc->sst['data'][$ind];

}


function convertUnicodeString( $str )
{
	for( $i=0; $i<strlen($str)/2; $i++ )
	{
		$no = $i*2;
		$hi = ord( $str[$no+1] );
		$lo = $str[$no];
		
		if( $hi != 0 )
			continue;
		elseif( ! ctype_alnum( $lo ) )
			continue;
		else
			$result .= $lo;
	}
	
	return $result;
}

function uc2html($str) {
	$ret = '';
	for( $i=0; $i<strlen($str)/2; $i++ ) {
		$charcode = ord($str[$i*2])+256*ord($str[$i*2+1]);
		$ret .= '&#'.$charcode;
	}
	return $ret;
}



function get( $exc, $data )
{
	switch( $data['type'] )
	{
		// string
	case 0:
		$ind = $data['data'];
		if( $exc->sst[unicode][$ind] )
			return htmlcode2utf(uc2html($exc->sst['data'][$ind]));
		else
			return $exc->sst['data'][$ind];

		// integer
	case 1:
		return (integer) $data['data'];

		// float
	case 2:
		return (float) $data['data'];
        case 3:
		return gmdate("m-d-Y",$exc->xls2tstamp($data[data]));

	default:
		return '';
	}
}



function fatal($msg = '') {
	echo '[Fatal error]';
	if( strlen($msg) > 0 )
		echo ": $msg";
	echo "<br>\nScript terminated<br>\n";
	if( $f_opened) @fclose($fh);
	exit();
}


function getTableData ( $ws, $exc ) {
	
	
	global $excel_file, $db_table;
	global $db_host, $db_name, $db_user, $db_pass;
	
	$data = $ws['cell'];
	
echo <<<FORM

	<form action="" method="POST" name="db_export">
        <div style="width:790px;height:800px;overflow:scroll;">
	<table border="0" cellspacing="1" cellpadding="2" align="center" width=1500 bgcolor="#666666">
        
	<tr bgcolor="#f1f1f1">

FORM;

// Form fieldnames
	
if ( !$_POST['useheaders'] ) {
	for ( $j = 0; $j <= $ws['max_col']; $j++ ) {

		$field = "field" . $j;
						
		echo <<<HEADER

		<td style="display:none;">
		<input type="checkbox" name="fieldcheck[$j]" value="$j" checked title="Check to proceed this field">
		<input type="text" name="fieldname[$j]" value="$field" title="Field name">
		</td>

HEADER;
	}
}
else {
	for ( $j = 0; $j <= $ws['max_col']; $j++ ) {
		
		$field = getHeader ( $exc, $data[0][$j] );
			
		$field = ereg_replace ( "^[0-9]+", "", $field );
		
		if (empty ($field) )
			$field = "field" . $j;
		
		echo <<<HEADER

		<td>
		<input type="checkbox" name="fieldcheck[$j]" value="$j" checked title="Check to proceed this field">
		<input type="text" name="fieldname[$j]" value="$field" title="Field name">
		</td>

HEADER;
	}
}

	
	echo "</tr>";
	
            foreach( $data as $i => $row ) { // Output data and prepare SQL instructions


                    if ( $i == 0 && $_POST['useheaders'] )
                    continue;

                    echo "<tr bgcolor=\"#ffffff\">";

                    for ( $j = 0; $j <= $ws['max_col']; $j++ ) {
                            $_w     =   "";
                            $cell = get ( $exc, $row[$j] );
                            if($j == 13){
                                $_w =   "width='400'";
                            }

                            if($i <1){
                                echo "<td $_w style='background-color:green;color:#EEE;'>$cell</td>";
                            }else{
                                echo "<td $_w>$cell</td>";
                            }

                    }

                    echo "</tr>";
                    $i++;
            }       
	
	if ( empty ( $db_table ) )
		$db_table = "Table1";
					
echo <<<FORM2
	
	</table><br>
        </div>
	<table align="center" width="390">	
	<tr><td></td><td><input type="hidden" name="excel_file" value="$excel_file">
	<input type="hidden" name="step" value="2">
	&nbsp;<input type="submit" name="submit" value="Output"></td></tr>
	</form>
        
	</table>
	<br>&nbsp;
FORM2;

} 



function prepareTableData ( $exc, $ws, $fieldcheck, $fieldname,$_photo_path='' ) {

	
	global $delivery,$mosConfig_absolute_path,$photos,$user_ids;
	getClass('product/entity/category');
        $cat    =   new Product_Enity_Category();                               
        include_once('includes/mark.gallery.php');        
        $files  =   scandir($_photo_path);    
            


	$data = $ws['cell'];
	$user_define_fieldname  =   array(0=>'id_product',1=>'name'
            );
        $now    =   date("Y-m-d H:i");
	foreach( $data as $i => $row ) { // Output data and prepare SQL instructions				
		if ( $i <= 1) // dong tieu de trong file excel
		continue;
		
		$SQL[$i] = "";
		
		for ( $j = 0; $j <= $ws['max_col']; $j++ ) {
		
                    if ( isset($fieldcheck[$j]) ) {

                            if($j == 10){
                                $delivery[$i]    =   addslashes ( get ( $exc, $row[$j] ) );
                            }                           

                            if($user_define_fieldname[$j]){
                                $SQL[$i] .= $user_define_fieldname[$j];
                                $SQL[$i] .= "=\"";
                                $SQL[$i] .= addslashes ( get ( $exc, $row[$j] ) );
                                $SQL[$i] .= "\"";
                                $SQL[$i] .= ",";
                            }
                    }
		}
                $user_ids[$i]   =   intval(get ( $exc, $row[16] ));
                $photo_absolute_path    =    ProtectedDirAbsolutePath($user_ids[$i]);
                if(!((file_exists($photo_absolute_path."/product")) && is_dir($photo_absolute_path."/product"))){
                    mkdir($photo_absolute_path."/product",0777);
                }
                $photo_absolute_path    =    str_replace($mosConfig_absolute_path, "", $photo_absolute_path);       
                
          
		$SQL[$i] = rtrim($SQL[$i], ',');		
		$i++;
	}
        
	return $SQL;	
			
} 


function ProtectedDirRelativePath($user_id){
        global $mosConfig_absolute_path;
        if(!((file_exists($mosConfig_absolute_path."/images/sites/" . $user_id)) && is_dir($mosConfig_absolute_path."/images/sites/" . $user_id)))
        {
                mkdir($mosConfig_absolute_path."/images/sites/" . $user_id,0777);
        }
        $protectedDir = "/images/sites/" . $user_id . '/protected' ;
        return $protectedDir;
}

function ProtectedDirAbsolutePath($user_id){
        global $mosConfig_absolute_path;

        $protectedDir = $mosConfig_absolute_path . ProtectedDirRelativePath($user_id);

        if(!((file_exists($protectedDir)) && is_dir($protectedDir)))
        {
                mkdir($protectedDir,0777);
        }        
        return $protectedDir;
}


function htmlcode2utf($str)
{
    $utf    =   '';
    $str_arr    =   explode('&#', $str);
    foreach($str_arr as $code)
    {
        $utf    .=  code2utf($code);
    }
    return $utf;
}

function code2utf($number)
{
if ($number < 0)
return FALSE;

if ($number < 128)
    return chr($number);

// Removing / Replacing Windows Illegals Characters
       if ($number < 160)
       {
               if ($number==128) $number=8364;
           elseif ($number==129) $number=160; // (Rayo:) #129 using no relevant sign, thus, mapped to the saved-space #160
           elseif ($number==130) $number=8218;
           elseif ($number==131) $number=402;
           elseif ($number==132) $number=8222;
           elseif ($number==133) $number=8230;
           elseif ($number==134) $number=8224;
           elseif ($number==135) $number=8225;
           elseif ($number==136) $number=710;
           elseif ($number==137) $number=8240;
           elseif ($number==138) $number=352;
           elseif ($number==139) $number=8249;
           elseif ($number==140) $number=338;
           elseif ($number==141) $number=160; // (Rayo:) #129 using no relevant sign, thus, mapped to the saved-space #160
           elseif ($number==142) $number=381;
           elseif ($number==143) $number=160; // (Rayo:) #129 using no relevant sign, thus, mapped to the saved-space #160
           elseif ($number==144) $number=160; // (Rayo:) #129 using no relevant sign, thus, mapped to the saved-space #160
           elseif ($number==145) $number=8216;
           elseif ($number==146) $number=8217;
           elseif ($number==147) $number=8220;
           elseif ($number==148) $number=8221;
           elseif ($number==149) $number=8226;
           elseif ($number==150) $number=8211;
           elseif ($number==151) $number=8212;
           elseif ($number==152) $number=732;
           elseif ($number==153) $number=8482;
           elseif ($number==154) $number=353;
           elseif ($number==155) $number=8250;
           elseif ($number==156) $number=339;
           elseif ($number==157) $number=160; // (Rayo:) #129 using no relevant sign, thus, mapped to the saved-space #160
           elseif ($number==158) $number=382;
           elseif ($number==159) $number=376;
       } //if

if ($number < 2048)
return chr(($number >> 6) + 192) . chr(($number & 63) + 128);
if ($number < 65536)
return chr(($number >> 12) + 224) . chr((($number >> 6) & 63) + 128) . chr(($number & 63) + 128);
if ($number < 2097152)
return chr(($number >> 18) + 240) . chr((($number >> 12) & 63) + 128) . chr((($number >> 6) & 63) + 128) . chr(($number & 63) + 128);


return FALSE;
}

?>